<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <el-breadcrumb-item v-for="item in levelList" :key="item.path">
      <span v-if="levelList.length === 1" class="no-redirect">{{ item.meta.title }}</span>
      <a v-else @click="handleLink(item)">{{ item.meta.title }}</a>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<script setup>
import { reactive, watchEffect } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const $router = new useRouter()
const $route = new useRoute()

const levelList = reactive([])

// 获取数据
function getBreadcrumb() {
  let matched = $route.matched.filter(item => item.meta && item.meta.title)
  // 如果之前数组存在数据就清空数组内容
  if (levelList.length > 0) levelList.length = 0
  levelList.push(...matched)
}

watchEffect(() => {
  getBreadcrumb()
})

// 点击跳转
function handleLink(item) {
  $router.push(item.redirect)
}
</script>

<style lang="scss" scoped>
.app-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>